package com.physics.mps.module.util;

import cn.hutool.core.io.FileUtil;
import org.springframework.beans.factory.annotation.Value;

import java.io.RandomAccessFile;

/**
 * 监测任务进度
 *
 * @author mcsoft
 * @since 2023/9/20
 */
public class TaskMonitor {
    @Value("${simulate.abaqus:.output-path}")
    private static String outputPath;


    private static float monitorTime(String jobName, float currentTime) {
        String staPath = outputPath + jobName + ".sta";
        //1.判断sta文件是否生成，若未生成则未开始计算
        if (!FileUtil.exist(staPath)) {
            return 0;
        }

        //2.读取staPath最后一行,如果最后一行为“ THE ANALYSIS HAS COMPLETED SUCCESSFULLY”则表示已经计算完成
        String lastLine = readLastLine(staPath);
        if (" THE ANALYSIS HAS COMPLETED SUCCESSFULLY".equals(lastLine)) {
            return -1;
        }

        //3.如果未计算完成，读取最后一行数据，获取当前时间步
        String[] frame = lastLine.split("\\s+");
        if (frame.length >= 8 && frame[7].matches("-?\\d+(\\.\\d+)?")) {
            return Float.valueOf(frame[7]);
        }

        return currentTime;
    }

    public static String readLastLine(String staPath) {
        RandomAccessFile file;
        try {
            file = new RandomAccessFile(staPath, "r");
            long fileLength = file.length();
            String lastLine = "";
            if (fileLength != 0L) {
                long pos = fileLength - 1;
                while (pos > 0) {
                    pos--;
                    file.seek(pos);
                    if (file.readByte() == '\n') {
                        lastLine = file.readLine();
                        break;
                    }
                }
            }
            file.close();
            return lastLine;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
